layui.define(['jquery', 'cascader', 'layer', 'rate', 'upload', 'form', 'laytpl', 'http', 'laydate', 'engine_table', 'table', 'public', 'iconHhysFa', 'slider', 'tinymce', 'iconPicker', 'tagsinput'], function (exports) {
    "use strict";

    let InitSetData = function (data = []) {
        data['button'] = 1;
        let urls = window.location.href;
        urls = urls.toLowerCase();
        if (urls.split('/detail').length >= 2) {
            data['button'] = 2;
        }
        let detail = data.detail || {};
        let PrintData = [];
        let html = $("#view_body_data").html();
        let TPL = $(html).get(0);
        $.each(detail, function (field, value) {
            let element = $(TPL).find('.' + field + '_box');
            let source = $(element).find('.layui-input-block').attr("data_source");
            if (source && value) {

            }
            let item = {
                field: field,
                value: value,
                title: $(element).find('.layui-form-label').text(),
                tag: $(element).find('.layui-input-block').attr("data_tag"),
                source: source,
            };
            if (field != 'id') {
                PrintData.push(item);
            }
        })
        PrintData = layui.public.spliceArr(PrintData, 1);
        let str = '<div style="padding: 15px">';
        str += '<div class="layui-btn-container noprint">';
        str += '<button type="button" class="layui-btn layui-btn-normal layui-btn-radius" onclick="jQuery.print()">打印页面</button>';
        // str += '<button type="button" class="layui-btn layui-btn-warm layui-btn-radius" onclick="jQuery.print()">导出PDF</button>';
        str += '</div>';
        str += '<table class="layui-table">';
        str += '<tr>';
        str += '<td colspan="2" style="text-align: center;font-weight: bold;font-size: 18px;padding: 15px">' + $("title").text() + '</td>';
        str += '</tr>';
        PrintData.forEach(item => {
            str += '<tr>';
            item.forEach(item2 => {
                let value = item2.value || '-';
                str += '<td style="background: #f8f8f8;width: 110px" >' + item2.title + '</td>';
                str += '<td>' + value + '</td>';
            });
            str += '</tr>';
        });
        str += '</table></div>';
        data['view'] = str;
        return data;
    }

    let BindShowTree = function (elem_id = '', field = '', options_num = '') {
        let data = InitData.source[options_num] || [];
        data = data.rows || [];
        let value = InitData.detail[field] || ''
        let treedata = TreeData(data, value);
        layui.tree.render({
            elem: "#showtree_" + elem_id,
            showCheckbox: true,
            data: treedata,
            id: elem_id,
            customName: {
                id: 'value',
                title: 'label',
                children: 'children'
            }
        });
    }

    let BindDateTime = function (elem_id = '', type = '', range = false, field = '', range_field = '') {
        let elem = "#focus_" + elem_id;
        if (range == 1) {
            range = '至';
        } else {
            range = false;
        }
        layui.laydate.render({
            elem: elem,
            type: type,
            fullPanel: true,
            range: range,
            done: function (value, date, endDate) {
                if (range_field && range) {
                    let item = value.split(range);
                    let start = item[0] || '';
                    let end = item[1] || '';
                    $("input[name='" + field + "']").val(start.trim());
                    $("input[name='" + range_field + "']").val(end.trim());
                }
            }
        });
    }
    let BindDateAll = function (elem_id, field) {
        let ids = 'laydate_' + elem_id;
        let elem = '#focus_' + elem_id;
        let initValue = InitData['detail'][field] || '';
        if (initValue) {
            initValue = initValue.split(',');
        } else {
            initValue = [];
        }
        let dateall = xmSelect.render({
            el: elem,
            content: '<div id="' + ids + '" />',
            height: 'auto',
            autoRow: true,
            name: field,
            on: function (data) {
                if (!data.isAdd) {
                    dateSelect(dateall.getValue('value'), ids);
                }
            }
        })
        layui.laydate.render({
            elem: '#' + ids,
            position: 'static',
            showBottom: false,
            change: function () {
                dateSelect(dateall.getValue('value'), ids);
            },
            done: function (value) {
                var values = dateall.getValue('value');
                var index = values.findIndex(function (val) {
                    return val === value
                });
                if (index != -1) {
                    values.splice(index, 1);
                } else {
                    values.push(value);
                }
                dateSelect(values, ids);
                dateall.update({
                    data: values.map(function (val) {
                        return {
                            name: val,
                            value: val,
                            selected: true,
                        }
                    })
                })
            },
            ready: function (date) {
                dateall.update({
                    data: initValue.map(function (val) {
                        return {
                            name: val,
                            value: val,
                            selected: true,
                        }
                    })
                })
                dateSelect(dateall.getValue('value'), ids);
            },

        })
    }

    let removeAll = function (ids = '') {

        document.querySelectorAll('#' + ids + ' td[lay-ymd].layui-this').forEach(function (dom) {
            dom.classList.remove('layui-this');
        });
    }

    let dateSelect = function (values, ids) {
        removeAll(ids);
        values.forEach(function (val) {
            var dom = document.querySelector('#' + ids + ' td[lay-ymd="' + val.replace(/-0([1-9])/g, '-$1') + '"]');
            dom && dom.classList.add('layui-this');
        });
    }

    let BindColor = function (elem_id) {
        let elem = '.focus_' + elem_id;
        layui.colorpicker.render({
            elem: elem,
            color: $("#focus_" + elem_id).val(),
            predefine: true,
            done: function (color) {
                let obj = $(this)[0].elem;
                let field = $(obj).attr('data-id');
                $("#" + field).val(color);
                SelectAction();
            }
        });
    }

    let BindSlider = function (elem_id = '', min = 1, max = 100) {

        layui.slider.render({
            elem: '#slider_' + elem_id,
            input: true, //输入框
            theme: theme_color,
            value: $("#focus_" + elem_id).val() || 0,
            min: Number(min),
            max: Number(max),
            done: function (value) {
                let obj = $(this)[0].elem;
                let field = $(obj).attr('data-id');
                $("#" + field).val(value);
                SelectAction();
            }
        });
    }

    let BindRate = function (elem_id) {
        layui.rate.render({
            elem: '.focus_' + elem_id,
            theme: theme_color,
            value: $("#focus_" + elem_id).val() || 0,
            choose: function (value) {
                var obj = $(this)[0].elem;
                var field = $(obj).attr('data-id');
                $("#" + field).val(value);
            }
        });
    }

    let BindHtmlEdit = function (elem_id, height = 400) {
        layui.tinymce.render({
            elem: "#focus_" + elem_id,
            height: height,
            forced_root_block: '',
            valid_elements: '*[*]',
            valid_children: '*[*]',
            images_upload_url: '/admin/file/upload/?t=tinymce',
            setup: function (editor) {
                editor.on('change', function () {
                    editor.save();
                });
            }
        });
    }
    let BindMarkDown = function (elem_id, height = 400) {
        editormd("markdown_" + elem_id, {
            width: "100%",
            height: height,
            syncScrolling: "single",
            path: "/static/component/markdown/editor/lib/",
            markdown: $("#focus_" + elem_id).val() || '',
            saveHTMLToTextarea: true,
            imageUpload: true,
            imageFormats: ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
            imageUploadURL: "/common/plugins/upload/?tag=markdown",
        });
    }

    let BindIcon = function (elem_id) {

        let length = $("#" + elem_id).find(".layui-form-select").length;
        if (length >= 1) {
            return;
        }


        let elem = "#focus_" + elem_id;
        let value = $(elem).val() || 'icon-keyboard-9';
        layui.iconHhysFa.render({
            elem: elem,
            type: 'awesome',
            url: '/static/component/pear/module/icon/icon.css',
            search: true,
            page: true,
            limit: 16,
            value: value,
            click: function (data) {
                SelectAction();
            },
            success: function (d) {

            }
        });
    }

    let BindUpload = function (elem_id, multiple, tag, type = '', size = '', file_num = 2) {

        UploadList(elem_id);
        let elem = "#upload_" + elem_id;
        let accept = "images";
        let acceptMime = "image/*";
        if (tag == "upfile") {
            accept = "file";
            acceptMime = '-';
        }
        file_num = file_num || 2;
        let token = localStorage.getItem('token') || '';
        layui.upload.render({
            elem: elem,
            url: '/common/plugins/upload/',
            accept: accept,
            size: size,
            multiple: multiple,
            headers: {token: token},
            acceptMime: acceptMime,
            number: Number(file_num),
            data: {
                tag: tag,
                type: type,
            },
            before: function (res) {
                layer.load();
            },
            done: function (res) {
                layui.layer.closeAll('loading');
                if (res.code == 200) {
                    let src = res.data.location || '';
                    let that = $(elem).parent('.upfile').parent('.layui-input-block');
                    let item = src;
                    let imgHtml = '<div class="upload_list">';
                    imgHtml += '<a href="javascript:void(0);" onClick="layui.public.delUploadFile(this)" class="img-file-del layui-icon layui-icon-close-fill"></a>';
                    let mime = layui.public.getMine(item);
                    switch (mime) {
                        case "png":
                        case "jpg":
                        case "jpeg":
                        case "gif":
                        case "ico":
                            imgHtml += '<img layer-src="' + item + '" src="' + item + '" alt="">';
                            break;
                        default:
                            imgHtml += '<div class="file_mime" onclick="layui.public.DownFile(\'' + item + '\')">' + mime + '</div>';
                    }
                    imgHtml += '</div>';
                    if (file_num == 2) {
                        $(that).find(".upload_list").remove();
                        $(that).find('.upload_con').append(imgHtml);
                        $(that).find(".upload_list").css('width', 'auto')
                        $(that).find('.layui-input').val(src);
                    } else {
                        $(that).find('.upload_con').append(imgHtml);
                        let input_val = $(that).find('.layui-input').val();
                        if (input_val) {
                            input_val += ",";
                        }
                        $(that).find('.layui-input').val(input_val + src);
                    }
                    layui.public.layerphotos($(that).find('.upload_list'));
                } else {
                    layui.layer.msg(res.msg, {icon: 2});
                }
            },
            error: function (res) {
                layui.layer.msg('请求出错，请稍后再试', {icon: 2});
            }
        })
    }
    let UploadList = function (elem_id) {
        let val = $("#focus_" + elem_id + "").val() || '';
        let name = $("#focus_" + elem_id + "").attr('name');
        let values = val.split(',');
        let str = '';
        values.forEach((item, index) => {
            if (item) {
                str += '<div class="upload_list">';
                str += '<a href="javascript:void(0);" onClick="layui.public.delUploadFile(this)" class="img-file-del layui-icon layui-icon-close-fill"></a>';
                let mime = layui.public.getMine(item);
                switch (mime) {
                    case "png":
                    case "jpg":
                    case "jpeg":
                    case "gif":
                    case "ico":
                        str += '<img layer-src="' + item + '" src="' + item + '" alt="" layer-index="' + index + '">';
                        break;
                    default:
                        str += '<div class="file_mime" onclick="layui.public.DownFile(\'' + item + '\')">' + mime + '</div>';
                }
                str += '</div>';
            }
        })
        $("." + name + "_box").find(".upload_con").html(str);
        layui.public.layerphotos($("." + name + "_box").find('.upload_list'));
    }

    let ChooseFile = function (elem_id = '', tag = '', file_num = '') {

        parent.layer.open({
            type: 2,
            offset: 'auto',
            title: '选择',
            area: ['700px', '620px'],
            scrollbar: true,
            content: '/common/plugins/uploadList/?file_num=' + file_num + '&tag=' + tag + '&elem_id=' + elem_id,
            btnAlign: 'r',
            btn: ['确定', '取消'],
            shade: 0.3,
            yes: function (index) {
                let iframe = parent.window['layui-layer-iframe' + index];
                let val = iframe.SendForm() || '';
                val = val.split(",").slice(0, -1).join(",");
                console.log(val);
                $("#focus_" + elem_id).val(val);
                UploadList(elem_id);
                let bindex = parent.layer.getFrameIndex('layui-layer-iframe' + index);
                parent.layer.close(bindex);
            }
        })
    }

    let BindTags = function (elem_id, placeholder) {
        let elem = "#focus_" + elem_id;
        $(elem).tagsInput({
            width: 'auto',
            defaultText: placeholder || '回车确定',
            height: '26px',
            hide: 1,
        })
    }

    let BindJsonTable = function (item = []) {

        let elem_id = item.elem_id;
        let tableid = 'table_' + elem_id;
        let value = $('#focus_' + elem_id).val() || '[]';
        let tag = item.tag || 'jsontable';
        value = eval(value);
        let cols = item.cols || [];
        let title = '';
        let caozuo = '';
        let url = '';
        let urls = item.urls || {};
        let is_curd = item.is_curd || 1;
        let is_all = item.is_all || 2;
        let choose_url = item.choose_url || '';
        let rule = item.rule || '';
        cols.unshift({title:'序号',type:'numbers',width:60});
        switch (tag) {
            case 'jsontable':
                if (is_curd == 1) {
                    let twidth=110;
                    title = '<div class="pear-btn pear-btn-smm btn_theme_1" onclick="layui.engine_table.AddTable(\'' + tableid + '\')">新增</div>';
                    if (choose_url) {
                        cols.forEach(item => {
                            let show_field = item.show_field || '';
                            if (show_field) {
                                rule += item.field + "||" + show_field + ',';
                            }
                        });
                        twidth=130;
                        rule = rule.substr(0, rule.length - 1);
                        choose_url = choose_url + '?choose=' + is_all;
                        title += '<div id="open_' + elem_id + '" data_tag="jsontable" data_url="' + choose_url + '" data_rule="' + rule + '" class="pear-btn pear-btn-smm btn_theme_2" onclick="layui.engine_table.ChooseTable(\'' + elem_id + '\')">选择</div>';
                    }
                    caozuo = {
                        title: title,
                        width: twidth,
                        tpl: '<div>' +
                            '<button type="button" class="pear-btn pear-btn-danger pear-btn-smm" onclick="layui.engine_table.DeleteTable(\'' + tableid + '\',{{d.LAY_INDEX}})"><i class="layui-icon layui-icon-delete"></i></button>' +
                            '<button type="button" class="pear-btn pear-btn-primary pear-btn-smm ruinuo-drag"><i class="layui-icon layui-icon-slider"></i></button>' +
                            '</div>'
                    };
                    cols.push(caozuo);
                }
                break;
            case "subtable":
                value = [];
                let d = layui.public.GetQueryAll() || {};
                let id = d.id || 0;
                if (id == 0) {
                    d.id = layui.public.RandomNumber();
                }
                $("#focus_" + elem_id).val(d.id);
                url = urls.lists || '';
                if (url) {
                    url = layui.public.GetUrl(d, url);
                }

                if (is_curd == 1) {
                    let add = urls.add || '';
                    add = layui.public.GetUrl(d, add);
                    let edit = urls.edit || '';
                    let del = urls.delete || '';
                    cols.forEach(item => {
                        let form_field = item.form_field || '';
                        if (form_field) {
                            add += '&' + item.field + '={' + form_field + '}';
                            edit += '&' + item.field + '={' + form_field + '}';
                        }
                    })
                    let name = urls.title || '';
                    let width = urls.width || 0;
                    let height = urls.height || 0;
                    title = '<div class="pear-btn pear-btn-smm btn_theme_1" onclick="layui.engine_form.SubTableOpen(\'' + add + '\',\'' + name + '\',' + width + ',' + height + ')">选择</div>';
                    caozuo = {
                        title: title,
                        width: 110,
                        tpl: '<div>' +
                            '<button type="button" class="pear-btn pear-btn-smm btn_theme_1" onclick="layui.engine_form.SubTableOpen(\'' + edit + '&id={{d.id}}\',\'' + name + '\',' + width + ',' + height + ')"><i class="ruinuo-icon icon-edit"></i></button>' +
                            '<button type="button" class="pear-btn pear-btn-smm btn_theme_2" onclick="layui.engine_form.SubTableDel(\'' + del + '?id={{d.id}}\',\'' + tableid + '\')"><i class="layui-icon layui-icon-delete"></i></button>' +
                            '</div>'
                    };
                    cols.push(caozuo);
                }
                break;
            case "choosetable":
                value = [];
                let add = urls.add || '';
                let lists = urls.lists || '';
                let val = $('#focus_' + elem_id).val() || 'none';
                if (lists) {
                    url = lists + '?choose_ids=' + val;
                }
                title = '<div id="open_' + elem_id + '" data_list_url="' + lists + '" data_tag="choosetable" data_url="' + add + '" data_rule="' + rule + '" class="pear-btn pear-btn-smm btn_theme_1" onclick="layui.engine_table.ChooseTable(\'' + elem_id + '\')">添加</div>';
                caozuo = {
                    title: title,
                    width: 110,
                    tpl: '<div>' +
                        '<button type="button" class="pear-btn pear-btn-smm btn_theme_2" onclick="layui.engine_form.ChooseTableDel(\'' + elem_id + '\',{{d.id}})"><span style="font-size: 12px">取消</span></button>' +
                        '</div>'
                };
                cols.push(caozuo);
                break;
        }
        let table = {
            style: 1,
            elem: tableid,
            url: url,
            limit: 0,
            page: false,
            cols: layui.engine_table.ColsAll(cols, tableid),
        }
        table['source'] = InitData['source'] || {};
        table['tag'] = tag;
        SettingData[tableid] = table;
        layui.engine_table.TableStyle(table, value);
    }
    let SubTableOpen = function (url, name, width = 0, height = 0) {
        let detail = InitData['detail'] || [];
        let d = {};
        $.each(detail, function (field, value) {
            let val = $("input[name='" + field + "'],select[name='" + field + "'],textarea[name='" + field + "']").val();
            d[field] = val;
        })
        url = layui.public.GetUrl(d, url);
        layui.public.OpenWindow(url, name, width, height);
    }

    let SubTableDel = function (url, tableid) {
        layui.public.OpenAjax(url, '刪除', 'layui.engine_table.SearchLoad(\'' + tableid + '\')');
    }

    let ChooseTableDel = function (elem_id = '', id = '') {
        let value = $("#focus_" + elem_id).val();
        let values = value.split(',');
        let ids = '';
        values.forEach(val => {
            if (val != id) {
                ids += val['id'] + ',';
            }
        })
        ids = ids.substr(0, ids.length - 1);
        $("#focus_" + elem_id).val(ids);
        ChooseTableInit(elem_id);
    }

    let ChooseTableInit = function (elem_id = '') {
        let list_url = $("#open_" + elem_id).attr('data_list_url');
        let tableelem = 'table_' + elem_id;
        let ids = $("#focus_" + elem_id).val() || 'none';
        list_url = list_url + '?choose_ids=' + ids;
        layui.table.reload(tableelem, {
            data: [], url: list_url,
        })
    }

    let BindRangeTime = function (elem_id = '', field = '', type = '') {
        var fields = field.split(',');
        var start = '#' + fields[0];
        var end = '#' + fields[1];
        layui.laydate.render({
            elem: "#focus_" + elem_id,
            type: type,
            range: [start, end],
        });
    }

    let BindSelect = function (elem_id, cat, field, options_num = [], is_all = 2, strict = false) {
        let radio = true;
        let clickClose = true;
        let icon = "hidden";
        if (is_all == 1) {
            radio = false;
            clickClose = false;
            icon = 'show';
            strict = true;
        }
        let data = InitData.source[options_num] || [];
        data = data.rows || [];
        let value = InitData.detail[field] || '';

        let initValue = '' + value + '' || '';
        if (initValue) {
            initValue = initValue.split(',');
        } else {
            initValue = [];
        }
        let tree_show = false;
        if (cat == 'tree') {
            tree_show = true;
            icon = 'show';
        }
        let cascader_show = false;
        if (cat == 'cascader') {
            cascader_show = true;
            let multiple = false;
            if (is_all == 1) {
                multiple = true;
            }

            let ids = '#focus_' + elem_id;
            let length = $("#" + elem_id).find(".el-cascader").length;
            if (length >= 1) {
                return;
            }
            if (!isNaN(value)) {
                value = parseInt(value);
            }
            if (multiple && value)
            {
                value=value.split(",");
            }
            let cas = layui.cascader({
                elem: ids,
                value: value,
                clearable: true,
                filterable: true,
                props: {
                    checkStrictly: false,
                    multiple: multiple
                },
                options: data//数据
            });
            cas.changeEvent(function (value, node) {

            });
            return;
        }


        xmSelect.render({
            prop: {
                name: 'label',
                value: 'value',
            },
            tree: {
                show: tree_show,
                expandedKeys: true,
                strict: strict,
            },
            model: {
                icon: icon
            },
            cascader: {
                show: cascader_show,
                strict: strict,
                indent: 200,
            },
            initValue: initValue,
            el: '#focus_' + elem_id,
            radio: radio,
            clickClose: clickClose,
            filterable: true,
            name: field,
            theme: {
                color: theme_color,
            },
            data: data,
            on: function (res) {
                try {
                    SelectAllAction(res, xm_field);
                } catch (err) {
                    console.log(err)
                }
            },
            done: function (res) {
                $("#focus_" + elem_id + " xm-select").click(function () {
                    xm_field = field;
                })
            }
        })
    }

    let TreeData = function (arr, value) {
        let values = value.split(',');
        for (let i = 0; i < arr.length; i++) {
            let val = arr[i]['value'] || '';
            let children = arr[i].children || [];
            if (children.length != 0) {
                arr[i].children = TreeData(children, value);
                arr[i].spread = true;
            } else {
                for (let ii = 0; ii < values.length; ii++) {
                    if (val == values[ii]) {
                        arr[i].checked = true;
                    }
                }
            }
        }
        return arr;
    }

    let CheckboxVal = function (v1 = '', v2 = '') {
        let value = 2;
        if (v2) {
            let arr = v2.split(',');
            arr.forEach(item => {
                if (item == v1) {
                    value = 1;
                }
            })
        }
        return value;
    }

    let SelectOption = function (arr = [], value = '') {
        let Option = '';
        arr.forEach(item => {
            let children = item.children || [];
            if (children.length == 0) {
                let selected = '';
                if (item.value == value) {
                    selected = " selected";
                }
                Option += '<option value="' + item.value + '"' + selected + '>' + item.label + '</option>';
            } else {
                Option += '<optgroup label="' + item.label + '">';
                for (var ii = 0; ii < children.length; ii++) {
                    var selected = '';
                    if (children[ii].value == value) {
                        selected = " selected";
                    }
                    Option += '<option value="' + children[ii].value + '"' + selected + '>' + children[ii].label + '</option>';
                }
                Option += '</optgroup>';
            }
        })
        return Option;
    }

    let BindOpenSelect = function (elem_id) {

        let name = $("#focus_" + elem_id).attr('name');
        let nameVal = $("#focus_" + elem_id).val() || '';
        let arr = nameVal.split(',');
        let html = '';
        arr.forEach((item, index) => {
            if (item) {
                html += '<li>' +
                    '<a href="javascript:void(0);" onClick="layui.engine_form.delOpenSelect(this,' + index + ',\'' + elem_id + '\')" class="layui-icon layui-icon-close-fill"></a>' +
                    '' + item + '' +
                    '</li>';
            }
        })
        $("." + name + "_box").find(".choose_list ").html(html);
    }

    let delOpenSelect = function (obj, index, elem_id) {

        let rule = $("#open_" + elem_id).attr("data_rule");
        let rules = rule.split(',');
        rules.forEach(item => {
            let c = item.split('||');
            let field = c[0];
            let elme = $("input[name='" + field + "'],select[name='" + field + "'],textarea[name='" + field + "']");
            let indexVal = $(elme).val() || '';
            let vals = indexVal.split(',');
            vals.splice(index, 1);
            let value = "";
            vals.forEach(item2 => {
                if (item2) {
                    value += item2 + ',';
                }
            })
            $(elme).val(value.substr(0, value.length - 1));
        })
        BindOpenSelect(elem_id);
        layui.layer.msg('删除成功');
    }

    let GetTreeData = function (arr) {
        let ids = '';
        for (let i = 0; i < arr.length; i++) {
            ids += arr[i]['value'] + ',';
            let children = arr[i].children || [];
            ids += layui.engine_form.GetTreeData(children);
        }
        return ids;
    }

    let GetFormData = function (fData, css = '') {
        let postData = eval(fData);
        let data = {};
        $.each(postData, function (field, value) {
            if (field != 'id') {
                data[field] = $("" + css + "input[name='" + field + "']," + css + "textarea[name='" + field + "']," + css + "select[name='" + field + "']").val();
                let tag = $("" + css + "input[name='" + field + "']," + css + "textarea[name='" + field + "']").attr('lay-tag') || '';
                switch (tag) {
                    case "radio":
                        data[field] = $("" + css + "input[name='" + field + "']:checked").val() || '';
                        break;
                    case "checkbox":
                        let checkbox = '';
                        $("" + css + "input[name='" + field + "']:checked").each(function () {
                            checkbox += $(this).attr('value') + ',';
                        })
                        data[field] = (checkbox.substring(checkbox.length - 1) == ',') ? checkbox.substring(0, checkbox.length - 1) : checkbox;
                        break;
                    case "switch":
                        data[field] = $("" + css + "input[name='" + field + "']").is(":checked") ? '1' : '2';
                        break;
                    case "jsontable":
                    case "subtable":
                        let json = $("" + css + "textarea[name='" + field + "']").val() || '[]';
                        data[field] = eval(json);
                        break;
                    case "showtree":
                        let eid = $("" + css + "input[name='" + field + "']").attr('id') || '';
                        let elem_id = eid.replace("focus_", "");
                        let checkedData = layui.tree.getChecked(elem_id);
                        let StrData = layui.engine_form.GetTreeData(checkedData);
                        data[field] = StrData.replace(/,([^,]*)$/, "$1")
                        break;
                }
            }
        });
        return data;
    }

    let ChangeOnclick = function (field = '') {
        /*点击事件*/
        let arr = form_config['onclick'] || [];
        let lists = [];
        arr.forEach(item => {
            if (item.tag != 'gongshi' && item['field'] == field) {
                lists.push(item);
            }
        })
        if (lists.length) {
            EndeOnclick(lists);
        }
    }

    let EndeOnclick = function (lists = []) {
        let value = '';
        let field = lists[0].field || '';
        let tag = lists[0].tag || '';
        switch (tag) {
            case "radio":
                value = $("input[name='" + field + "']:checked").val() || '';
                break;
            case "select":
                value = $("select[name='" + field + "']").val() || '';
                break;
        }
        lists.forEach(item => {
            $('.' + item['event_field'] + '_box').hide();
            $('.' + item['event_field'] + '_box .layui-form-label').removeClass('layui-form-item-required');
            let event_val = item['event_val'] || '';
            let show = 2;
            switch (item['event_type']) {
                case ">":
                    if (Number(event_val) > Number(value)) {
                        show = 1;
                    }
                    break;
                case "<":
                    if (Number(event_val) < Number(value)) {
                        show = 1;
                    }
                    break;
                case "=":
                    if (event_val == value) {
                        show = 1;
                    }
                    break;
                case "!=":
                    if (event_val != value) {
                        show = 1;
                    }
                    break;
                case ">=":
                    if (Number(event_val) >= Number(value)) {
                        show = 1;
                    }
                    break;
                case "<=":
                    if (Number(event_val) <= Number(value)) {
                        show = 1;
                    }
                    break;
                case "in":
                    if (event_val.indexOf(value) !== -1) {
                        show = 1;
                    }
                    break;
                case "notin":
                    if (event_val.indexOf(value) <= -1) {
                        show = 1;
                    }
                    break;
            }
            let field_val = item['field_val'] || '';
            if (field_val) {
                $('.' + item['event_field'] + '_box').find("input,select").val('');
            }
            if (show == 1) {
                $('.' + item['event_field'] + '_box').show();
                let required = item['required'] || 2;
                if (required == 1) {
                    $('.' + item['event_field'] + '_box .layui-form-label').addClass('layui-form-item-required');
                }
                if (field_val) {
                    $('.' + item['event_field'] + '_box').find("input,select").val(field_val);
                }
            }
        })
        layui.form.render();
    }


    let ChangeAction = function () {
        layui.form.on('select(select_filter)', function (data) {
            let elem = data.elem;
            let field = $(elem).attr('name');
            ChangeOnclick(field);
        })

        layui.form.on('radio(radio_filter)', function (data) {
            let elem = data.elem;
            let field = $(elem).attr('name');
            ChangeOnclick(field);
        })
        layui.form.on('checkbox(checkbox_filter)', function (data) {
            let elem = data.elem;
            let field = $(elem).attr('name');
            ChangeOnclick(field);
        })
    }

    let GetFollow = function (obj) {
        var value = $(obj).val();
        layui.layer.prompt({title: '请输入信息', formType: 2}, function (val, index) {
            if (val) {
                if (value) {
                    var content = layui.public.DateNow() + '  ' + val + '\r\n' + value;
                } else {
                    var content = layui.public.DateNow() + '  ' + val;
                }
                $(obj).val(content);
            }
            layui.layer.close(index);
        });
    }

    let BindMap = function (obj) {
        let url = '/common/component/baidumap/';
        parent.layer.open({
            type: 2,
            offset: 'auto',
            title: '地图',
            area: ['90%', '620px'],
            scrollbar: true,
            content: url,
            btnAlign: 'r',
            btn: ['确定', '取消'],
            shade: 0.3,
            yes: function (index) {
                let iframe = parent.window['layui-layer-iframe' + index];
                let val = iframe.SendVal() || '';
                $(obj).val(val);
                let bindex = parent.layer.getFrameIndex('layui-layer-iframe' + index);
                parent.layer.close(bindex);
            }
        })
    }

    let BindCode = function (elem_id, field) {
        let obj = '.' + field + '_box';
        $('' + obj + ' input,' + obj + ' textarea').on('change', function () {
            let src = $('#code_' + elem_id).attr('src');
            let srcs = src.split('text=');
            $('#code_' + elem_id).attr('src', srcs[0] + 'text=' + $(this).val());
        });
    }

    let BindEvent = function () {
        $(".ruinuo_flex").each(function () {
            $(this).find('.design-box').eq(0).removeClass('layui-col-xs12 layui-col-md12')
        })
        let arr = form_config.onclick || [];
        arr.forEach(item => {
            switch (item.tag) {
                case "gongshi":
                    let fields = GetMatchField(item.gongshi_txt);
                    fields.forEach(item2 => {
                        if (item2.tag == 'input' || item2.tag == 'textarea') {
                            let obj = '.' + item2['field'] + '_box';
                            $('' + obj + ' input,' + obj + ' textarea').on('change', function () {
                                EventGongshi(item.field)
                            })
                        } else {
                            $("." + item2.field + "_box").find('select,input').attr('data_gongshi', item.field);
                        }
                    })

                    break;
                default:
                    $("." + item.field + "_box").find('select,input').attr('data_event', item.field);
            }
        })
        arr.forEach(item => {
            let that = $("." + item.field + "_box").find('select,input');
            let EventVal = $(that).attr('data_event') || '';
            let GongshiVal = $(that).attr('data_gongshi') || '';
            if (EventVal || GongshiVal) {
                let ClassVal = $(that).attr('data_add') || 'no';
                if (ClassVal.split('bindevent').length != 2) {
                    $(that).attr('lay-filter', 'filter_' + item.field);
                    $(that).attr('data_add', '1');
                    if (EventVal) {
                        ChangeOnclick(EventVal);
                    }
                    layui.form.on(item.tag + '(filter_' + item.field + ')', function (data) {
                        if (EventVal) {
                            ChangeOnclick(EventVal);
                        }
                        if (GongshiVal) {
                            EventGongshi(GongshiVal);
                        }
                    })
                }
            }
        })


    }

    let EventGongshi = function (field) {
        let arr = form_config.onclick || [];
        let gongshi = '';
        arr.forEach(item => {
            if (item.tag == 'gongshi' && item.field == field) {
                gongshi = item.gongshi_txt;
            }
        })
        if (gongshi && field) {
            const regex = /\{([\s\S]*?)\}/g;
            let match;
            let str = gongshi;
            while ((match = regex.exec(gongshi))) {
                let obj = '.' + match[1] + '_box';
                let value = $('' + obj + ' input,' + obj + ' textarea,' + obj + ' select').val() || 0;
                str = str.replace("{" + match[1] + "}", value);
            }
            $('.' + field + '_box').find('input').val(eval(str));
        }
    }


    let GetMatchField = function (value = '') {
        const regex = /\{([\s\S]*?)\}/g;
        let match;
        let fields = [];
        while ((match = regex.exec(value))) {
            let obj = '.' + match[1] + '_box';
            let tag = $(obj).find(".layui-input-block").attr('data_tag');
            fields.push({field: match[1], tag: tag});
        }
        return fields;
    }
    let SelectAction = function () {

    }
    let SelectAllAction = function () {

    }


    let SendData = function () {
        let detail = InitData.detail || {};
        let PostData = GetFormData(detail);
        let id = detail.id || '';
        let PostUrl = form_config.add;
        if (id) {
            PostData['id'] = id;
            PostUrl = form_config.edit
        }
        let data = {
            PostUrl: PostUrl,
            PostData: PostData
        }
        return data;
    }

    let SendBack = function (res) {

        if (res.code == 200) {
            layer.msg('提交成功，即将跳转页面', {
                icon: 1,
                time: 1000
            }, function () {
                if (window.parent == window.self) {
                    init();
                    return;
                }
                try {
                    let td_elem = layui.public.GetQuery('elem') || 'datatable';
                    let detail = InitData.detail || {};
                    let id = detail.id || '';
                    window.parent.layer.close(parent.layer.getFrameIndex(window.name));
                    window.parent.SearchLoad(td_elem, id);
                } catch (err) {
                    init();
                }
            });
            return;
        }
        let field = res.data.field || '';
        if (field) {
            let fields = field.split("||");
            let obj = '';
            if (fields.length == 1) {
                obj = $("input[name='" + field + "'],textarea[name='" + field + "'],select[name='" + field + "']");
            } else {
                obj = $("." + fields[0] + "_box").find("input[name='" + fields[1] + "']").eq(fields[2]);
            }

            $(obj).focus();
            $(obj).addClass('layui-form-danger');
            layer.msg(res.msg, {icon: 2});
            return;
        }
        layer.alert(res.msg, {icon: 2, title: '温馨提示'});
    }

    let LoadData = function () {
        let PostData = layui.public.GetQueryAll() || {};
        let urls = window.location.href;
        urls = urls.toLowerCase();
        if (urls.split('/edit').length >= 2) {
            PostData['node'] = 'edit';
        }
        if (urls.split('/add').length >= 2) {
            PostData['node'] = 'add';
        }
        let PostUrl = form_config.detail;
        let data = {
            PostUrl: PostUrl,
            PostData: PostData
        }
        return data;
    }

    let LoadBack = function (res) {
        if (res.code != 200) {
            layer.alert(res.msg, {icon: 2, title: '温馨提示'}, function (index) {
                parent.layer.close(parent.layer.getFrameIndex(window.name));
            })
            return;
        }
        InitData = layui.engine_form.InitSetData(res.data);
        if (InitData.button == 2) {
            $(".view_body").html(InitData.view);
            return;
        }
        layui.public.ViewTpl(InitData, 'view_body_data', 'view_body');
        FormBind();
        layui.engine_form.BindEvent();
    }
    let PowerField = function (field = '') {
        let power = InitData.power || {};
        return power[field] || 2;
    }


    let EngineForm = {
        InitSetData: InitSetData,
        BindShowTree: BindShowTree,
        BindDateTime: BindDateTime,
        BindDateAll: BindDateAll,
        BindColor: BindColor,
        BindSlider: BindSlider,
        BindRate: BindRate,
        BindHtmlEdit: BindHtmlEdit,
        BindMarkDown: BindMarkDown,
        BindIcon: BindIcon,
        BindSelect: BindSelect,
        BindUpload: BindUpload,
        UploadList: UploadList,
        BindTags: BindTags,
        BindJsonTable: BindJsonTable,
        TreeData: TreeData,
        CheckboxVal: CheckboxVal,
        SelectOption: SelectOption,
        removeAll: removeAll,
        dateSelect: dateSelect,
        BindOpenSelect: BindOpenSelect,
        delOpenSelect: delOpenSelect,
        GetTreeData: GetTreeData,
        GetFormData: GetFormData,
        ChangeOnclick: ChangeOnclick,
        EndeOnclick: EndeOnclick,
        ChangeAction: ChangeAction,
        GetFollow: GetFollow,
        BindMap: BindMap,
        BindCode: BindCode,
        BindEvent: BindEvent,
        GetMatchField: GetMatchField,
        EventGongshi: EventGongshi,
        SelectAction: SelectAction,
        SelectAllAction: SelectAllAction,
        SendData: SendData,
        SendBack: SendBack,
        LoadData: LoadData,
        LoadBack: LoadBack,
        ChooseFile: ChooseFile,
        PowerField: PowerField,
        SubTableDel: SubTableDel,
        SubTableOpen: SubTableOpen,
        ChooseTableDel: ChooseTableDel,
        ChooseTableInit: ChooseTableInit,
    };
    exports('engine_form', EngineForm);
});
